package com.job;

import com.domain.myenum.AuctionStatusEnum;
import com.google.common.collect.Maps;
import com.handler.email.Email;
import com.handler.email.EmailHandler;
import com.mapper.self.AdviceMapper;
import com.mapper.self.AuctionMapper;
import com.mapper.self.CompanyMapper;
import com.pojo.ShAuction;
import com.pojo.ShCompany;
import com.service.user.UserService;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.util.HashMap;

/**
 * Created by Huoyunren on 2016/5/26.
 */
public class AuctionJob implements Job {
  private static final Logger LOG = LoggerFactory.getLogger(AuctionJob.class);
  @Autowired
  private AuctionMapper auctionMapper;
  @Autowired
  private AdviceMapper adviceMapper;
  @Autowired
  private EmailHandler emailHandler;
  @Autowired
  private CompanyMapper companyMapper;

  @Override
  public void execute(JobExecutionContext context) throws JobExecutionException {
    LOG.info("拍卖时间到，定时任务执行...");
    String uuid = context.getMergedJobDataMap().getString("uuid");
    String auctionEmail = context.getMergedJobDataMap().getString("auctionEmail");
    ShAuction auction = auctionMapper.queryLatestByUuid(uuid);
    int status = AuctionStatusEnum.Over.getCode();
    String dealEmail = null;
    BigDecimal dealPrice = null;
    if (auction == null) {
      status = AuctionStatusEnum.TimeOut.getCode();
      adviceMapper.changeAuctionStatus(uuid, status, dealEmail, dealPrice);
      return;
    }
    dealEmail = auction.getEmail();
    dealPrice = auction.getPrice();
    adviceMapper.changeAuctionStatus(uuid, status, dealEmail, dealPrice);
    ShCompany company = companyMapper.queryByEmail(dealEmail);
    String[] to = {auctionEmail, dealEmail};
    emailNotify(to, dealPrice,company.getPhone(),company.getEmail(),company.getName());
  }

  public void emailNotify(String[] to, BigDecimal price,String dealPhone,String dealEmail,String dealName) {
    Email email = new Email();
    email.setTemplate("auction.ftl");
    email.setTo(to);
    email.setEnableHtml(Boolean.TRUE);
    email.setSubject("拍卖通知");
    HashMap<String, Object> map = Maps.newHashMap();
    map.put("dealPrice", "￥" + price);
    map.put("dealPhone",dealPhone);
    map.put("dealEmail",dealEmail);
    map.put("dealName",dealName);
    email.setMap(map);
    emailHandler.asyncSendMail(email);
  }
}
